/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.se2.meteocal.gui;

import it.polimi.se2.meteocal.control.CalendarManager;
import it.polimi.se2.meteocal.control.EmailSender;
import it.polimi.se2.meteocal.control.EventManager;
import it.polimi.se2.meteocal.control.LocationManager;
import it.polimi.se2.meteocal.control.NotificationManager;
import it.polimi.se2.meteocal.control.ParticipationManager;
import it.polimi.se2.meteocal.control.UserManager;
import it.polimi.se2.meteocal.entity.Calendar;
import it.polimi.se2.meteocal.entity.Event;
import it.polimi.se2.meteocal.entity.Location;
import it.polimi.se2.meteocal.entity.Participation;
import it.polimi.se2.meteocal.entity.ParticipationNotification;
import it.polimi.se2.meteocal.entity.Users;
import it.polimi.se2.meteocal.helper.DateUtilityMethods;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Named;


/**
 *
 * @author Ugo
 */
@Named
@RequestScoped

public class newEventBean {
    
  
    @EJB
    private EventManager eventManager;
    
    @EJB
    private CalendarManager calendarManager;
    
    @EJB
    private UserManager userManager;
    
    @EJB
    private LocationManager locationManager;
    
    @EJB
    private ParticipationManager participationManager;
    
    @EJB
    private NotificationManager notificationManager;
   
    private Date begin;
    private Date end;
    private Event event;
    private String location;
    private List<Users> users;
    private List<String> participants;
    private final EmailSender emailsender=new EmailSender();
    
    @PostConstruct
    public void init(){
        users = userManager.findOtherUsers();
    }
    
    public newEventBean(){
   
    }
    public List getUsers(){
        return users;
    }
    
    public void setUsers(List Users ){
        this.users=Users;
    }
    public void setLocation(String location){
       this.location=location;    
    }
    
    public void setParticipants(List participants ){
        this.participants=participants;
    }
    
    public List getParticipants(){
        return this.participants;
    }
    
    public String getLocation(){
        return this.location;
    }
    public Date getBegin() {
        return begin;
    }

    public void setBegin(Date begin) {
        this.begin = begin;
    }

    public Date getEnd() {
        return end;
    }

    public void setEnd(Date end) {
        this.end = end;
    }
    
     public Event getEvent(){
        if(event==null){
            event = new Event();
        }
        return event;
    }
    
    public void createEvent(){
      List<Participation> partev=new ArrayList();
      if(DateUtilityMethods.isInconsistency(begin,end)==false){
        if(checkEventConflict()==false){
            try{
                Calendar cal= calendarManager.findCalendarByUser(userManager.getLoggedUser());
                locationManager.create(new Location(location));
                event.setLocation(new Location(location));
                event.setCalendar(cal);
                event.setBeginn(new Time(this.begin.getHours(), this.begin.getMinutes(), 0));
                event.setEndd(new Time(this.end.getHours(), this.end.getMinutes(), 0));
                eventManager.create(event);
                //LA PAGINA MI DA I RISULTATI IN STRINGHE NON IN USER, QUINDI INTERROGO LO USERMANAGER PER TALI STRINGHE RESTITUENDOMI LO USER
                for(String s: participants){
                    Participation part = new Participation(userManager.findUserByEmail(s),event);
                    participationManager.create(part);
                    partev.add(part);
                    //RIEMPIO LA PARTICIPATION NOTIFICATION RELATIVA ALLA PARTECIPAZIONE SOPRA CREATA
                    ParticipationNotification partnot= new ParticipationNotification();
                    partnot.setParticipation(part);
                    partnot.setSeen(false);
                    partnot.setType(Long.valueOf(1));
                    notificationManager.create(partnot);
                }
                
                message("Event created and added to your calendar",FacesMessage.SEVERITY_INFO);
                }
            catch(EJBException ejbe){
                FacesContext context = FacesContext.getCurrentInstance();
                context.addMessage(null, new FacesMessage("Creation failed."));   
            }
        }
        else
            message("Event not created. Event conflict detected",FacesMessage.SEVERITY_WARN);
      }
      else
           message("Pay attention. Begin time must be less than end time",FacesMessage.SEVERITY_WARN);
      if(partev.size()>0)
        emailsender.sendEmailInvitation(partev, event);
    }
    
    private boolean checkEventConflict(){
        List <Event>  events= calendarManager.findEventsInCalendar(calendarManager.findCalendarByUser(userManager.getLoggedUser()));
        Date de1,de2;
        de1= DateUtilityMethods.DateAndTime(event.getData(),new Time(this.begin.getHours(), this.begin.getMinutes(),0));
        de2= DateUtilityMethods.DateAndTime(event.getData(),new Time(this.end.getHours(), this.end.getMinutes(),0));
        for(Event e:events){
            Date dx1,dx2;
            dx1= DateUtilityMethods.DateAndTime(e.getData(),new Time(e.getBeginn().getHours(), e.getBeginn().getMinutes(),0));
            dx2= DateUtilityMethods.DateAndTime(e.getData(),new Time(e.getEndd().getHours(), e.getEndd().getMinutes(),0));
            if(DateUtilityMethods.isOverlapped(de1, de2, dx1, dx2))
                return true;
        }
        return false;
    }
        
     private void message(String string, FacesMessage.Severity  type){
        FacesContext context = FacesContext.getCurrentInstance(); 
        context.addMessage(null, new FacesMessage(type,"", string));
    }
}